package com.zlp.controller;

import com.alibaba.fastjson.JSONObject;
import com.zlp.dto.SyncUploadReportReq;
import com.zlp.utils.FileUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;

// https://www.imooc.com/article/309351
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("upload")
public class UpDownLoadTests {

    @Resource
    private RestTemplate restTemplate;


    @GetMapping("uploadTest")
    public String uploadTest() {

        // http://127.0.0.1:8110/upload/uploadTest

        MultiValueMap<String, Object> bodyParams = new LinkedMultiValueMap<>();
//      String filePath = "D:\\file\\video\\图片1\\1.jpg";
        String filePath = "D:\\file\\oss\\001.jpg";

        // 封装请求参数
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        bodyParams.add("file", resource);
        bodyParams.add("personId", "p0001");
        bodyParams.add("reportNo", "b0001");
        bodyParams.add("category", 0);
        bodyParams.add("sourceUrl", "http://127.0.0.1:8088/oss/file/uploadFile");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("Authorization", UUID.randomUUID().toString());
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyParams, headers);
        String url = "http://127.0.0.1:8088/oss/file/uploadFile";
        String returnVo = restTemplate.postForObject(url, requestEntity, String.class);
        return returnVo;
    }

    /**
     * 1. 本地云上传文件
     *  2. 两个对象文件{type = 1 fsdffdsf
     *  type = 2  fsdfsdfs
     *  3. 补偿机制文件
     *  }
     *
     * 1.
     *  远程下载zipjar
     * @param response
     * @date: 2021/5/31 10:40
     */
    @GetMapping("downloadTest")
    public void downloadTest(HttpServletResponse response,Integer fileType) {
        String fileName = null;
        if (Objects.isNull(fileType)) fileType = 2;
        if (fileType == 1) {
            fileName = "纸质报告.zip";
        }else if (fileType == 2){
            fileName = "报告源数据.zip";
        }else if (fileType == 3) {
            fileName = "报告全部源数据源.zip";
        }
        // 1|2|3|4|5|5||||||||||||||||||||||||||||||||||
        String url = "http://127.0.0.1:8088/oss/file/downloadLocalFile?fileName="+fileName;
        ResponseEntity<byte[]> rsp = restTemplate.getForEntity(url,byte[].class);
        BufferedInputStream bis = null;
        if (Objects.nonNull(rsp)) {
            byte[] body = rsp.getBody();
            if (Objects.nonNull(body)) {
                try {
                    log.info("文件大小==>:{}", body.length);
                    String filename = fileName;
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
                    InputStream is = new ByteArrayInputStream(body);
                    bis = new BufferedInputStream(is);
                    OutputStream os = response.getOutputStream();
                    byte[] buffer = new byte[2048];
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    /**
     *  将字符串以文件的方式上传
     *
     * @param url 上传的接口 url
     * @param content 上传的字符串内容
     * @param fileName 文件的名称
     * @return  RestTemplate 的请求结果
     * @author daleyzou
     */
    public static ResponseEntity<String> postFileData(String url, String content, String fileName) {
        RestTemplate client = new RestTemplate();
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("filename", fileName);
        // 构建字节流数组
        ByteArrayResource resource = new ByteArrayResource(content.getBytes()) {
            @Override
            public String getFilename() {
                // 文件名
                return fileName;
            }
        };
        param.add("file", resource);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param,headers);
        ResponseEntity<String> exchange = client.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange;
    }

    @GetMapping("uploadFileTest")
    public String uploadFileTest() {

        String url = "http://127.0.0.1:8088/oss/file/uploadStaticFile";
        String filename = "1.html";
        String content = "\n" +
                "<!DOCTYPE html>\n" +
                "<html lang=en>\n" +
                "<head>\n" +
                "  <meta charset=UTF-8>\n" +
                "  <meta name=viewport content=\"width=device-width,initial-scale=1\">\n" +
                "  <meta name=\"Description\" Content=\"燧人医疗自成立之初，就致力于研究大脑健康和认知规律。我们不断探索，深耕于脑机接口技术，从MPU（思维处理器）芯片、人工智能算法、传感器，再到大脑数据的不断实验和研究，聚焦在联脑计算领域，以期为全人类提供可靠的全新脑机设备。2019年，我们与张江国家实验室脑与智能科技研究院共同成立了“联脑工程联合实验室”，以张旭院士为首的顶级神经领域科学家带队，招募了一大批海内外知名学者，在脑科学领域砥砺前行。\">\n" +
                "  <link rel=\"icon\" href=\"./favicon.ico\">\n" +
                "  <title>燧人（上海）医疗科技有限公司-新闻详情</title>\n" +
                "  <link rel=\"stylesheet\" href=\"./css/bootstrap.min.css\">\n" +
                "  <link rel=\"stylesheet\" href=\"./plugins/video/video-js.min.css\" rel=\"stylesheet\">\n" +
                "  <link rel=\"stylesheet\" href=\"./css/common.css\">\n" +
                "  <link rel=\"stylesheet\" href=\"./css/newsinfo.css\">\n" +
                "</head>\n" +
                "<body>\n" +
                "  <div class=\"container-fluid newsInfo-page page-container\">\n" +
                "    <div class=\"title-wrap\">\n" +
                "      <h1 class=\"news-title font-superBold\">中华医学会神经病学分会考察团来访我司深入了解脑功能评估筛查系统</h1>\n" +
                "      <p class=\"news-time\">2021-06-06 16:05:06</p>\n" +
                "    </div>\n" +
                "    <div class=\"new-container\"><p style=\"text-indent: 2em;\">6月6日上午，中国医师协会神经内科医师分会候任会长、中华医学会神经病学分会痴呆和认知障碍学组组长、福建医科大学校长陈晓春教授（下图左四）协同首都医科大学附属北京天坛医院神经病学中心认知障碍性疾病科主任施炯教授（下图左三）以及相关随行人员一同莅临我司深入调研脑功能评估筛查系统，我司CEO蔡江（下图右三）全程陪同并对产品性能及规划一一讲解。&nbsp;</p><p style=\"text-indent: 2em;\"><br/></p><p style=\"text-align:center\"><img src=\"https://greenvalley.oss-cn-shanghai.aliyuncs.com/suirenow/6f4973496c4e4aadae7a5f3525f77661.png\" width=\"1200\" style=\"width: 1200px; height: 700px;\" height=\"700\" border=\"0\" vspace=\"0\" alt=\"\"/></p><p style=\"text-align: left; text-indent: 2em;\"><span style=\"text-indent: 2em;\"><br/></span></p><p style=\"text-align: left; text-indent: 2em;\"><span style=\"text-indent: 2em;\">陈晓春教授和施炯教授对我司产品-脑功能评估筛查系统表现出了浓厚的兴趣，他们先是仔细听取了产品汇报，随后又亲自体验了产品检测过程并当下决定加入到产品的临床试验合作项目。陈晓春教授表示此款设备的出现对于认知领域的疾病能够树立一道有效的筛查防线，做到早筛查早发现早治疗。仪器的早日应用对于完成国健委提出的双80%（注释1）目标会是一个行之有效的助力器。施炯教授表示，一切都是从病人的需要出发，阿尔茨海默症的防治需要更多像燧人医疗一样有社会责任感的有技术实力的企业参与，各方多交流探讨，一起努力共同推进完成双80%（注释1）的目标。</span></p><p style=\"text-align: left; text-indent: 2em;\"><span style=\"text-indent: 2em;\"><br/></span></p><p style=\"text-align: left; text-indent: 2em;\"><span style=\"text-indent: 2em;\"></span></p><p style=\"text-align: center\"><img src=\"https://greenvalley.oss-cn-shanghai.aliyuncs.com/suirenow/31e239cd0d59445e9b6e5ada0cdd8960.png\" width=\"1200\" style=\"width: 1200px; height: 834px;\" height=\"834\" border=\"0\" vspace=\"0\" alt=\"\"/></p><p><br/></p><p style=\"text-align: center\"><img src=\"https://greenvalley.oss-cn-shanghai.aliyuncs.com/suirenow/ccf289188cef4a22af0c18ce19eeac5d.png\" width=\"1200\" style=\"width: 1200px; height: 883px;\" height=\"883\" border=\"0\" vspace=\"0\" alt=\"\"/></p><p><br/></p><p style=\"text-indent: 2em;\">我司CEO蔡江表示脑功能评估筛查系统充分结合了多种数据采集和分析技术，把最前沿的科研成果应用到产品上是为了更好的体验度和更准确的检测报告输出。目前多方交流反馈给了他更大的信心，他相信燧人医疗的愿景（守卫人类大脑健康）一定能早日实现。</p><p style=\"text-indent: 2em;\"><br/></p><p><span style=\"color: #A5A5A5;\">注释1：为了预防和减缓痴呆和认知障碍的发生，国家卫健委在2020年刊发了《探索痴呆防治特色服务工作方案》，方案确定了试点地区到2022年的工作目标，包括公众对老年痴呆防治知识知晓率达80%，建立健全老年痴呆防治服务网络，建立健全患者自我管理、家庭管理、社区管理、医院管理相结合的预防干预模式，社区（村）老年人认知功能筛查率达80%。</span></p><p><span style=\"color: #A5A5A5;\"></span></p><p style=\"text-align: left; text-indent: 2em;\"><span style=\"text-indent: 2em;\"></span><br/></p></div>\n" +
                "  </div>\n" +
                "</body>\n" +
                "<script src=\"https://cdn.bootcss.com/popper.js/1.14.7/umd/popper.min.js\"></script>\n" +
                "<script type=\"text/javascript\" src=\"./js/jquery-3.4.1.min.js\"></script>\n" +
                "<script type=\"text/javascript\" src=\"./js/bootstrap.min.js\"></script>\n" +
                "<script type=\"text/javascript\" src=\"./js/http.js\"></script>\n" +
                "<script type=\"text/javascript\" src=\"./js/siteLayout.js\"></script>\n" +
                "<script type=\"text/javascript\" src=\"./plugins/video/video.min.js\"></script>\n" +
                "</html>\n" +
                "  ";
        ResponseEntity<String> resp = postFileData(url,content,filename);
        if (resp.getStatusCode().equals(HttpStatus.OK)) {
            String body = resp.getBody();
            log.info("uploadFileTest.resp body={}",body);
            return body;
        }
        return null;
    }
}